package com.sihai.ehr.web.action.ajax;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.TrainMaterResource;
import com.sihai.ehr.model.biz.TrainPlan;
import com.sihai.ehr.model.biz.TrainPlanDutyTarget;
import com.sihai.ehr.model.biz.TrainPlanEmployeeTarget;
import com.sihai.ehr.model.biz.TrainRealiaResource;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.TrainAssessService;
import com.sihai.ehr.service.TrainMaterResourceService;
import com.sihai.ehr.service.TrainPlanDutyTargetService;
import com.sihai.ehr.service.TrainPlanEmployeeTargetService;
import com.sihai.ehr.service.TrainPlanService;
import com.sihai.ehr.service.TrainRealiaResourceService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.TrainAssessPojo;
import com.sihai.ehr.web.pojo.TrainPlanDutyTargetPojo;
import com.sihai.ehr.web.pojo.TrainPlanEmployeeTargetPojo;

/**
 * 培训管理AJAX类
 * 
 * @author henry
 * 
 */
public class TrainJsonControl extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private DutyService dutyService;
	@BeanInject
	private EmployeeService employeeService;
	@BeanInject
	private TrainAssessService trainAssessService;
	@BeanInject
	private TrainPlanService trainPlanService;
	@BeanInject
	private TrainMaterResourceService trainMaterResourceService;
	@BeanInject
	private TrainRealiaResourceService trainRealiaResourceService;
	@BeanInject
	private TrainPlanDutyTargetService trainPlanDutyTargetService;
	@BeanInject
	private TrainPlanEmployeeTargetService trainPlanEmployeeTargetService;

	private List<TrainAssessPojo> assessPojos;
	private String weightTitle;
	private Long planId;

	// 教育资源属性 //
	/** 课件名称 */
	private String coursewareName;
	/** 课件URL地址 */
	private String coursewareUrl;
	/** 上传者 */
	private String uploader;

	// 教具资源 //
	private String resIds;
	private int year;
	private TrainPlan plan;

	// private String dutytarget;
	// private String duty_outing_target;
	private Long dutyId;
	private Float credit;
	private Long workId;
	List<TrainPlanDutyTargetPojo> targets;
	List<TrainPlanEmployeeTargetPojo> employeePojos;

	@Action(value = "/ajax/train_assess_employees", results = { @Result(name = "success", type = "json", params = {
			"root", "assessPojos" }) })
	public String getAssessListByPlanId() {
		try {
			assessPojos = trainAssessService.getTrainAssessPojos(planId,
					weightTitle, 0, null, null);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}

	@Action(value = "/ajax/train_materresource_upload", results = { @Result(name = "success", type = "plainText") })
	public String saveTrainMaterresourceUpload() {
		if (planId == null || planId < 0) {
			return ERROR;
		}
		if (coursewareName == null || coursewareName.isEmpty()) {
			return ERROR;
		}
		try {
			TrainPlan plan = trainPlanService.getTrainPlan(planId);
			TrainMaterResource resource = new TrainMaterResource();
			resource.setTrainPlan(plan);
			resource.setCoursewareName(coursewareName);
			resource.setCoursewareUrl(coursewareUrl);
			resource.setUploadDate(new Date(System.currentTimeMillis()));
			resource.setUploader(uploader);

			// 保存教育资源
			trainMaterResourceService.save(resource);

			// 更新培训计划
			plan = trainPlanService.getTrainPlan(planId);
			plan.setLastuploadDate(resource.getUploadDate());
			trainPlanService.save(plan);

			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write("success");
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return ERROR;
		}
	}

	/**
	 * 保存计划教具对象
	 * 
	 * @return
	 */
	@Action(value = "/ajax/post_planrealia_resource", results = { @Result(name = "success", type = "plainText") })
	public String savePlanRealiaResource() {
		if (planId == null || planId < 0) {
			return ERROR;
		}
		if (resIds.isEmpty() || resIds == null) {
			return ERROR;
		}
		try {
			TrainPlan plan = trainPlanService.getTrainPlan(planId);
			plan.getRealiaResources().clear(); // 先请除
			for (String s : resIds.split(",")) {
				TrainRealiaResource realiaResource = trainRealiaResourceService
						.getTrainRealiaResource(Long.parseLong(s));
				plan.getRealiaResources().add(realiaResource);
			}
			// 更新计划
			trainPlanService.save(plan);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write("success");
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}

	/**
	 * 查询组织部门内聘培训对象配置分数
	 * 
	 * @return
	 */
	@Action(value = "/ajax/query_dutytarget_credit", results = { @Result(name = "success", type = "plainText") })
	public String queryDutyTargetCreditByOrgId() {
		try {
			Double totalCount = trainPlanDutyTargetService
					.getTotalCountCreditByOrganizationId(organizationId, year);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(
					totalCount == null ? "0" : totalCount.toString());
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 查询配置对象
	 * 
	 * @return
	 */
	@Action(value = "/ajax/query_dutytarget", results = { @Result(name = "success", type = "plainText") })
	public String queryDutyTargetByPlanId() {
		try {
			StringBuffer sbResult = new StringBuffer();

			TrainPlan plan = trainPlanService.getTrainPlan(planId);
			if (plan.getLecturerType() == 0) {
				List<TrainPlanDutyTarget> targets = trainPlanDutyTargetService
						.getTrainPlanDutyTargets(planId, null, null);
				for (TrainPlanDutyTarget trainPlanDutyTarget : targets) {
					sbResult.append(trainPlanDutyTarget.getDuty().getDutyName())
							.append(",");
				}
			} else {
				List<TrainPlanEmployeeTarget> targets = trainPlanEmployeeTargetService
						.getTrainPlanEmployeeTargets(planId, null, null);
				for (TrainPlanEmployeeTarget trainPlanEmployeeTarget : targets) {
					sbResult.append(
							trainPlanEmployeeTarget.getEmployeeinfoWork()
									.getBaseId().getName()).append(",");
				}
			}
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(
					sbResult.length() > 0 ? sbResult.substring(0,
							sbResult.length() - 1) : "无培训对象");
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

	@Action(value = "/ajax/train-apply-form-save", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String saveToPlanSession() throws Exception {
		if (plan != null) {
			plan.setLecturerType(0);
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		plan.setPlanStartDate(formatter.parse(getParameter("planStartDate")));
		plan.setPlanEndDate(formatter.parse(getParameter("planEndDate")));
		ServletActionContext.getRequest().getSession()
				.setAttribute("current_plan_form", plan);
		return SUCCESS;
	}

	@Action(value = "/ajax/train-plan-dutytarget-save", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String saveToDutyTargetSession() throws Exception {
		if (organizationId != null && organizationId > 0 && dutyId != null
				&& dutyId > 0) {
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			// 检测是否存在
			List<TrainPlanDutyTargetPojo> dutyTargets = null;
			if (session.getAttribute("dutytarget") != null) {
				dutyTargets = (List<TrainPlanDutyTargetPojo>) session
						.getAttribute("dutytarget");
				if (dutyTargets != null && dutyTargets.size() > 0) {
					boolean isHaset = false;
					Iterator<TrainPlanDutyTargetPojo> it = dutyTargets.iterator();
					while (it.hasNext()) {
						TrainPlanDutyTargetPojo dutyTarget = it.next();
						if (dutyTarget.getDutyId().longValue() == dutyId.longValue()) {
							isHaset = true;
							dutyTarget.setCredit(credit);
						}
					}

					if (!isHaset) {
						TrainPlanDutyTargetPojo dutyTarget = new TrainPlanDutyTargetPojo();
						dutyTarget.setOrganizationId(organizationId);
						dutyTarget.setDutyId(dutyId);
						dutyTarget.setDutyName(dutyService.get(dutyId).getDutyName());
						dutyTarget.setCredit(credit);
						dutyTargets.add(dutyTarget);
					}
				} else {
					dutyTargets = new ArrayList<TrainPlanDutyTargetPojo>();
					TrainPlanDutyTargetPojo dutyTarget = new TrainPlanDutyTargetPojo();
					dutyTarget.setOrganizationId(organizationId);
					dutyTarget.setDutyId(dutyId);
					dutyTarget.setDutyName(dutyService.get(dutyId).getDutyName());
					dutyTarget.setCredit(credit);
					dutyTargets.add(dutyTarget);
				}
			} else {
				dutyTargets = new ArrayList<TrainPlanDutyTargetPojo>();
				TrainPlanDutyTargetPojo dutyTarget = new TrainPlanDutyTargetPojo();
				dutyTarget.setOrganizationId(organizationId);
				dutyTarget.setDutyId(dutyId);
				dutyTarget.setDutyName(dutyService.get(dutyId).getDutyName());
				dutyTarget.setCredit(credit);
				dutyTargets.add(dutyTarget);
			}
			session.setAttribute("dutytarget", dutyTargets);

		}
		return SUCCESS;
	}

	/** 删除职务选择对象 */
	@Action(value = "/ajax/train-plan-dutytarget-remove", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String removeToDutyTargetSession() throws Exception {
		if (organizationId != null && organizationId > 0 && dutyId != null
				&& dutyId > 0) {
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			// 检测是否存在
			List<TrainPlanDutyTargetPojo> dutyTargets = null;
			if (session.getAttribute("dutytarget") != null) {
				dutyTargets = (List<TrainPlanDutyTargetPojo>) session
						.getAttribute("dutytarget");
				if (dutyTargets != null && dutyTargets.size() > 0) {
					boolean isHaset = false;
					Iterator<TrainPlanDutyTargetPojo> it = dutyTargets.iterator();
					while (it.hasNext()) {
						TrainPlanDutyTargetPojo dutyTarget = it.next();
						if (dutyTarget.getDutyId().longValue() == dutyId.longValue()) {
							it.remove();
						}
					}
					session.setAttribute("dutytarget", dutyTargets);
				}
			}

		}
		return SUCCESS;
	}

	@Action(value = "/ajax/train_dutytargets", results = { @Result(name = "success", type = "json", params = {
			"root", "targets" }) })
	public String asyncSelectedDutyTarget() {
		try {
			targets = new ArrayList<TrainPlanDutyTargetPojo>();
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			if (session.getAttribute("dutytarget") != null) {
				targets = (List<TrainPlanDutyTargetPojo>) session
						.getAttribute("dutytarget");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}

	/**
	 * 检测选择的职务对象
	 * 
	 * @return
	 */
	@Action(value = "/ajax/check_dutytarget", results = { @Result(name = "success", type = "plainText") })
	public String checkSelectDutyTarget() {
		try {

			HttpServletResponse response = ServletActionContext.getResponse();
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			if (session.getAttribute("dutytarget") != null) {
				response.getWriter().write("1");
			} else {
				response.getWriter().write("0");
			}
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}
	
	//////////////////////////////////////////////
	/**
	 * 外训处理模块
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/ajax/train-outing-apply-form-save", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String saveToOutingPlanSession() throws Exception {
		if (plan != null) {
			plan.setLecturerType(1);
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		plan.setPlanStartDate(formatter.parse(getParameter("planStartDate")));
		plan.setPlanEndDate(formatter.parse(getParameter("planEndDate")));
		ServletActionContext.getRequest().getSession()
				.setAttribute("current_plan_form", plan);
		return SUCCESS;
	}

	@Action(value = "/ajax/train-plan-employeetarget-save", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String saveToEmployeeTargetSession() throws Exception {
		if (organizationId != null && organizationId > 0 && dutyId != null
				&& dutyId > 0 && workId != null && workId > 0) {
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			// 检测是否存在
			List<TrainPlanEmployeeTargetPojo> employeeTargets = null;
			if (session.getAttribute("duty_outing_target") != null) {
				employeeTargets = (List<TrainPlanEmployeeTargetPojo>) session
						.getAttribute("duty_outing_target");
				if (employeeTargets != null && employeeTargets.size() > 0) {
					boolean isHaset = false;
					Iterator<TrainPlanEmployeeTargetPojo> it = employeeTargets
							.iterator();
					while (it.hasNext()) {
						TrainPlanEmployeeTargetPojo employeeTarget = it.next();
						if (employeeTarget.getWorkId().longValue() == workId.longValue()) {
							isHaset = true;
						}
					}

					if (!isHaset) {
						TrainPlanEmployeeTargetPojo employeeTarget = new TrainPlanEmployeeTargetPojo();
						employeeTarget.setOrganizationId(organizationId);
						employeeTarget.setDutyId(dutyId);
						employeeTarget.setWorkId(workId);
						employeeTarget.setWorkName(employeeService.getEmployeeinfoWork(workId).getBaseId().getName());
						employeeTargets.add(employeeTarget);
					}
				} else {
					employeeTargets = new ArrayList<TrainPlanEmployeeTargetPojo>();
					TrainPlanEmployeeTargetPojo employeeTarget = new TrainPlanEmployeeTargetPojo();
					employeeTarget.setOrganizationId(organizationId);
					employeeTarget.setDutyId(dutyId);
					employeeTarget.setWorkId(workId);
					employeeTarget.setWorkName(employeeService.getEmployeeinfoWork(workId).getBaseId().getName());
					employeeTargets.add(employeeTarget);
				}
			} else {
				employeeTargets = new ArrayList<TrainPlanEmployeeTargetPojo>();
				TrainPlanEmployeeTargetPojo employeeTarget = new TrainPlanEmployeeTargetPojo();
				employeeTarget.setOrganizationId(organizationId);
				employeeTarget.setDutyId(dutyId);
				employeeTarget.setWorkId(workId);
				employeeTarget.setWorkName(employeeService.getEmployeeinfoWork(workId).getBaseId().getName());
				employeeTargets.add(employeeTarget);
			}
			session.setAttribute("duty_outing_target", employeeTargets);

		}
		return SUCCESS;
	}

	/** 删除员工选择对象 */
	@Action(value = "/ajax/train-plan-employeetarget-remove", results = { @Result(name = "success", type = "json", params = {
			"root", "result" }) })
	public String removeToEmployeeTargetSession() throws Exception {
		if (organizationId != null && organizationId > 0 && dutyId != null
				&& dutyId > 0 && workId != null && workId > 0) {
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			// 检测是否存在
			List<TrainPlanEmployeeTargetPojo> employeeTargets = null;
			if (session.getAttribute("duty_outing_target") != null) {
				employeeTargets = (List<TrainPlanEmployeeTargetPojo>) session
						.getAttribute("duty_outing_target");
				if (employeeTargets != null && employeeTargets.size() > 0) {
					boolean isHaset = false;
					Iterator<TrainPlanEmployeeTargetPojo> it = employeeTargets
							.iterator();
					while (it.hasNext()) {
						TrainPlanEmployeeTargetPojo employeeTarget = it.next();
						if (employeeTarget.getWorkId().longValue() == workId.longValue()) {
							it.remove();
						}
					}
					session.setAttribute("duty_outing_target", employeeTargets);
				}
			}

		}
		return SUCCESS;
	}

	@Action(value = "/ajax/train_employeetargets", results = { @Result(name = "success", type = "json", params = {
			"root", "employeePojos" }) })
	public String asyncSelectedEmployeeTarget() {
		try {
			employeePojos = new ArrayList<TrainPlanEmployeeTargetPojo>();
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			if (session.getAttribute("duty_outing_target") != null) {
				employeePojos = (List<TrainPlanEmployeeTargetPojo>) session
						.getAttribute("duty_outing_target");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}

	/**
	 * 检测外训员工选择对象
	 * 
	 * @return
	 */
	@Action(value = "/ajax/check_employeetarget", results = { @Result(name = "success", type = "plainText") })
	public String checkSelectEmployeeTarget() {
		try {

			HttpServletResponse response = ServletActionContext.getResponse();
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			if (session.getAttribute("duty_outing_target") != null) {
				response.getWriter().write("1");
			} else {
				response.getWriter().write("0");
			}
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

	public List<TrainAssessPojo> getAssessPojos() {
		return assessPojos;
	}

	public void setAssessPojos(List<TrainAssessPojo> assessPojos) {
		this.assessPojos = assessPojos;
	}

	public String getWeightTitle() {
		return weightTitle;
	}

	public void setWeightTitle(String weightTitle) {
		this.weightTitle = weightTitle;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	public String getCoursewareName() {
		return coursewareName;
	}

	public void setCoursewareName(String coursewareName) {
		this.coursewareName = coursewareName;
	}

	public String getCoursewareUrl() {
		return coursewareUrl;
	}

	public void setCoursewareUrl(String coursewareUrl) {
		this.coursewareUrl = coursewareUrl;
	}

	public String getUploader() {
		return uploader;
	}

	public void setUploader(String uploader) {
		this.uploader = uploader;
	}

	public String getResIds() {
		return resIds;
	}

	public void setResIds(String resIds) {
		this.resIds = resIds;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public TrainPlan getPlan() {
		return plan;
	}

	public void setPlan(TrainPlan plan) {
		this.plan = plan;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	public Float getCredit() {
		return credit;
	}

	public void setCredit(Float credit) {
		this.credit = credit;
	}

	public Long getWorkId() {
		return workId;
	}

	public void setWorkId(Long workId) {
		this.workId = workId;
	}

	public List<TrainPlanDutyTargetPojo> getTargets() {
		return targets;
	}

	public void setTargets(List<TrainPlanDutyTargetPojo> targets) {
		this.targets = targets;
	}

	public List<TrainPlanEmployeeTargetPojo> getEmployeePojos() {
		return employeePojos;
	}

	public void setEmployeePojos(List<TrainPlanEmployeeTargetPojo> employeePojos) {
		this.employeePojos = employeePojos;
	}
}
